#include <REGX52.H>
#include <stdio.h>
#include <string.h>
#include "i2c.h"
#include "eeprom.h"
#include "zuzhiduizhao.h"

#define isReadAddr 0
#define isWifiLinkAddr 1
#define wenDu1Addr 2

// 开启SmartConfig配网模式
void startConfig();
// 停止启SmartConfig配网模式
void stopConfig();
// 开启tcp
void startService();

// 解析串口数据
void decode(char str);
// 发生数据
void sendByte(unsigned char sdata);
// 发生数据
void sendData(char *str);
// 执行单片机命令
void cmd(char *str);
// 温度数值转摄氏度
int convert(unsigned char num);
// 数字转字符串
int intToStr(int num, char *str);
// 软件延时
void Delay100ms(int num);		//@11.0592MHz
void Delay100ms1(int num);		//@12.000MHz
// 串口中断
void UartInit1(void);		//4800bps@12.000MHz
void UartInit(void);		//4800bps@11.0592MHz


char shuzi[6] = {0};
char dataCmd[19] = {0};
char dataUart[20] = {0};
char wendu[3]={0};
char id = 0;

// 开启SmartConfig配网模式相关命令
// 停止 SmartConfig
const char code CWSTOPSMART[]="AT+CWSTOPSMART\r\n";
// 断开与 AP 的连接
const char code CWQAP[]="AT+CWQAP\r\n";
// 设置Station 模式
const char code CWMODE[]="AT+CWMODE=1\r\n";
// 开启 SmartConfig
const char code CWSTARTSMART[] = "AT+CWSTARTSMART\r\n";

// 开启tcp相关命令
// 设置TCP多连接
const char code CIPMUX[] ="AT+CIPMUX=1\r\n";
// 开启TCP连接9999端口
const char code CIPSERVER[] = "AT+CIPSERVER=1,9999\r\n";

void main(void){
	unsigned char tmp=1;
	unsigned char modeFlay;
	UINT8 isRead;
 
	Delay100ms(20);//等待硬件初始化
	
	UartInit();
	// 是否擦除过数据
	isRead = EEPROMReadByte(isReadAddr);
	if(isRead != '1'){
		EEPROMSectorErase(0);
		EEPROMWriteByte(isReadAddr,'1');
	}
	modeFlay = EEPROMReadByte(isWifiLinkAddr);
	//未连接过wifi
	if(modeFlay!='1'){
		P1_0=0;
		startConfig();
		P1_1=0;
	}else{
		startService();
		P1_0=1;
		wendu[0] = EEPROMReadByte(wenDu1Addr);
	}
	while(1){
		P1_5=!P1_5;
		//tmp = uread();
		Delay100ms(10);
		//tmp = convert(tmp);
		//intToStr(tmp,shuzi);
		//sendByte(tmp);
	} 
}

void sendByte(unsigned char sdata){
	SBUF = sdata;
		while(!TI);
		TI=0;
}

void sendData(unsigned char *sdata){
	while(*sdata!='\0'){
		sendByte(*sdata);
		sdata++;
	}
}
void startConfig(){
	stopConfig();
	sendData(CWQAP);
	Delay100ms(10);
	sendData(CWMODE);
	Delay100ms(10);
	sendData(CWSTARTSMART);
	Delay100ms(10);
}
void stopConfig(){
	sendData(CWSTOPSMART);
	Delay100ms(10);
}
void startService(){
	sendData(CIPMUX);
	Delay100ms(10);
	sendData(CIPSERVER);
	Delay100ms(10);
}

void sendTCP(unsigned char *sdata,int num,int tongdao){
	sprintf(dataCmd, "%c,%d\r\n",id, num+2);
	sendData("AT+CIPSEND=");
	sendData(dataCmd);
	Delay100ms(5);
	sendByte('0'+tongdao);
	sendByte(':');
	sendData(sdata);
}

void decode(char str)
{
    static char i = 0;
    static char j = 0;
    static char dataLen = 0;
    static char cmdFlag = 0; // 0:接收命令 1：接收数据

	if(i<20){
			dataCmd[i] = str;
		}
    if (dataCmd[0] == '+' || dataCmd[0] == 's'|| dataCmd[0] == 'W')
    {
        i++;
    }
    else
    {
        i = 0;
    }

    if (dataCmd[0] == '+' && dataCmd[1] == 'I')
    {
        if (i == 6)
        {
            id = str;
        }
        else if (dataCmd[1] == 'I' && i > 7 && cmdFlag == 0)
        {
            if (str == ':')
            {
                cmdFlag = 1;
                j = 0;
            }
            else
            {
                dataLen *= 10;
                dataLen += (str - '0');
            }
        }
        else if (dataCmd[1] == 'I' && i > 7 && cmdFlag == 1)
        {
            dataUart[j] = str;
            j++;
        };
					
        if (dataLen > 0 && dataLen == j)
        {
            dataUart[j] = '\0';
            cmd(dataUart);
            dataLen = 0;
            j = 0;
            i = 0;
            cmdFlag = 0;
            memset(dataCmd, 0, 19);
            memset(dataUart, 0, 20);
        }
    }else if(dataCmd[0] == 'W' && dataCmd[5] == 'G' && i==6){
				stopConfig();
				startService();
				P1_1=1;
				EEPROMWriteByte(isWifiLinkAddr,'1');
		}
		if(str == '\r' || str == '\n'){
			dataLen = 0;
			j = 0;
			i = 0;
			cmdFlag = 0;
			memset(dataCmd, 0, 20);
			memset(dataUart, 0, 30);
		}
}
/**
 * 执行命令
 */
void cmd(char *str)
{
		unsigned char datas='0';
		unsigned char i=0;
		unsigned char *token;
		P1_2=!P1_2;
		sendData(str);
    if (strncmp(str, "S1,",3) == 0)
    {
			P1_3=!P1_3;
			token = strtok(str, ",");
			token = strtok(NULL, ",");
			wendu[0]=token[0];
			EEPROMWriteByte(wenDu1Addr,wendu[0]);

    }else if (strcmp(str, "S1") == 0)
    {
			for(i=0;i<8;i++){
					datas = uread((int)(i/2));
					if(i%2==1){
						datas = intToStr(convert(datas),shuzi);
						sendTCP(shuzi,datas,(int)(i/2));
						Delay100ms(1);
					}
			}
    }
}
// 温度数值转摄氏度
int convert(unsigned char num){
	int i=0;
	for(i=0;i<121;i++){
		if(wenduNum[i]==num){
			return i-10;
		}else if(wenduNum[i]<num){
			return i-10;
		}
	}
	return 121;
}
int intToStr(int num, char *str) {
    int start;
    int end;
    int i = 0;
    int isNegative = 0;

    // 处理负数
    if (num < 0) {
        isNegative = 1;
        num = -num;
    }

    // 处理数字
    do {
        str[i++] = (num % 10) + '0';
        num /= 10;
    } while (num > 0);
    // 添加负号
    if (isNegative) {
        str[i++] = '-';
    }

    // 添加终止符
		str[i]='\0';
		// 反转字符串
    start = 0;
    end = i - 1;
    while (start < end) {
        char temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }
		return i;
}

/**
void Delay100ms1(int num)		//@12.000MHz
{
	unsigned char i, j;

	while(num>0){
		num--;
		i = 195;
		j = 138;
		do
		{
			while (--j);
		} while (--i);
	}
}
*/
void Delay100ms(int num)		//@11.0592MHz
{
	unsigned char i, j;
	while(num>0){
			num--;
		i = 180;
		j = 73;
		do
		{
			while (--j);
		} while (--i);
	}
}

/**
void UartInit1(void)		//4800bps@12.000MHz
{
	SCON=0X50;			//设置为工作方式1
	TMOD=0X20;			//设置计数器工作方式2
	PCON=0X80;			//波特率加倍
	TH1=0XF3;				//计数器初始值设置，注意波特率是4800的
	TL1=0XF3;
	ES=1;						//打开接收中断
	EA=1;						//打开总中断
	TR1=1;					//打开计数器
}
*/
void UartInit(void)		//4800bps@11.0592MHz
{
	PCON &= 0x7F;		//波特率不倍速
	SCON = 0x50;		//8位数据,可变波特率
	TMOD &= 0x0F;		//清除定时器1模式位
	TMOD |= 0x20;		//设定定时器1为8位自动重装方式
	TL1 = 0xFA;		//设定定时初值
	TH1 = 0xFA;		//设定定时器重装值
	ET1 = 0;		//禁止定时器1中断
	TR1 = 1;		//启动定时器1
	ES=1;						//打开接收中断
	EA=1;						//打开总中断
	TR1=1;					//打开计数器
}

// 接收串口信息
void Usart() interrupt 4
{
	unsigned char receiveData;
	receiveData=SBUF;
	if(RI==1){
		RI = 0;
		decode(receiveData);		
	}
}
